var answerKeyRegex = /^vote::([^:]+)::([^:]+)$/;

var optionKeyPrefix = 'option_';
var optionKeyPrefixLength = optionKeyPrefix.length;

var voteKeyPrefix = 'vote::';
var voteKeyPrefixLength = voteKeyPrefix.length;


function createModelFromState() {
    model = new Model();

    addOptionsToModel();
    addVotesToModel();
}


function addOptionsToModel() {
    var state = wave.getState();
    var state_keys = state.getKeys();

    for ( var idx in state_keys) {
	var key = state_keys[idx];
	_addOptionIfIsOptionKey(key, state.get(key));
    }
}

function _addOptionIfIsOptionKey(key, caption) {
    if (isOptionKey(key)) {
	model.options[key] = new Option(key, caption);
    }
}

function isOptionKey(key) {
    return (optionKeyPrefix == key.substr(0, optionKeyPrefixLength));
}

function addVotesToModel() {
    var state = wave.getState();
    var state_keys = state.getKeys();
    var removedOldKey = false;

    for ( var idx in state_keys) {
	var key = state_keys[idx];
	try {
	    _addKeyIfIsVoteKey(key, state.get(key));
	} catch (err) {
	}
    }

    if (removedOldKey) {
	throw "Removed old votes";
    }

    return model;
}

function _addKeyIfIsVoteKey(key, voting) {
    var isVoteKey = (voteKeyPrefix == key.substr(0, voteKeyPrefixLength));

    if (isVoteKey) {
	var vote = _createVote(key, voting);
	if (!model.options[vote.optionId]) {
	    var state = wave.getState();
	    state.submitValue(key, null);
	    throw "Removed old vote";
	}
	model.options[vote.optionId].voters.push(vote.participantId);
	model.votes[key] = vote;
    }
}

function _createVote(voteId, answer) {
    var match = answerKeyRegex.exec(voteId);

    if (match == null) {
	throw "Match was null, not expected!";
    }

    var optionId = match[1];
    var participantId = match[2];

    return new Vote(optionId, participantId, answer);
}

function extractOptionIdFromVoteId(voteId) {
    var match = answerKeyRegex.exec(voteId);

    if (match == null) {
	throw "Match was null, not expected!";
    }

    var optionId = match[1];
    return optionId;
}
